//
//  CYCreditVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/5/7.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCreditVController.h"
#import "CYCreditTool.h"
#import "CYDefaultRecordAO.h"
#import "MBProgressHUD+LE.h"
#import "CYDefaultRecordCell.h"
#import "CYDetailHeadView.h"
#import "CYCreditDetailTVController.h"
#import "CYNavigationVController.h"
#import "MJRefresh.h"
#import "CYEscape.h"
#import "CYCreditCacheTool.h"
#import "CYCitysPickerView.h"
#import <CoreLocation/CoreLocation.h>
#import "CYPayBack.h"
#import "CYJumpsTool.h"
#import "CYLoginHttpTool.h"
#import "CYCreditDetailVC.h"
#import "LEDIYFooter.h"
#import "CYCompanyUserTool.h"
#import "CYCompanyUserModel.h"

static NSString *CYSearchKey = @"CYSearchKey";

@interface CYCreditVController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, CYCitysPickerViewDelegate, CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UISearchBar *creditSearchBar;
@property (weak, nonatomic) IBOutlet UITableView *creditTableView;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (weak, nonatomic) IBOutlet UIButton *coverBtn;
@property (weak, nonatomic) IBOutlet UIView *areView;
@property (strong,nonatomic) UIView *noticeview;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableviewConstraint;//底部约束

@property (copy, nonatomic) NSString *searchText;
@property (strong, nonatomic) NSMutableArray *newsDefaults;//黑名单数据
@property (strong, nonatomic) NSMutableArray *searchResult;//搜索数据
@property (strong, nonatomic) NSArray *payBacks;//还款展示数据
@property (strong, nonatomic) NSMutableArray *showDatas;//显示的数据

@property (weak, nonatomic) MJRefreshAutoNormalFooter *footer;//底部刷新
@property (assign, nonatomic) __block int page;//页码
@property (strong, nonatomic) NSMutableDictionary *searchKeyDic;//搜索关键字

@property (strong, nonatomic) NSNumber *total;
@property (weak, nonatomic) CYCitysPickerView *pickerView;//地区筛选框
@property (assign, nonatomic, getter=isShow) BOOL show;//地区筛选框是否显示

@property (nonatomic, strong) CLLocationManager *locMgr;

@property (nonatomic, assign) NSInteger segmentSelected;//选中的segment

@property (nonatomic, assign) int y;//当前tableview的y值
//黑名单加载更多
@property(nonatomic, strong) NSString *city;
@property(nonatomic, assign) NSInteger defPage;
@end

@implementation CYCreditVController

- (NSMutableDictionary *)searchKeyDic {
    if (!_searchKeyDic) {
        _searchKeyDic = [NSMutableDictionary dictionaryWithDictionary:CYUserDefaultsGetObj(CYSearchKey)];
        if (!_searchKeyDic) {
            _searchKeyDic = [NSMutableDictionary dictionary];
        }
    }
    return _searchKeyDic;
}

- (CLLocationManager *)locMgr {
    if (!_locMgr) {
        self.locMgr = [[CLLocationManager alloc] init];
        
        self.locMgr.delegate = self;
    }
    return _locMgr;
}

- (NSMutableArray *)newsDefaults {
    if (!_newsDefaults) {
        _newsDefaults = [NSMutableArray array];
    }
    return _newsDefaults;
}

- (void)setSearchText:(NSString *)searchText {
    _searchText = [searchText copy];
    
    //根据条件搜索本地数据
    searchText = searchText.uppercaseString;
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ or certificateNo contains %@ or phone contains %@", searchText, searchText, searchText];
    //    self.searchResult = [NSMutableArray arrayWithArray:[self.newsDefaults filteredArrayUsingPredicate:predicate]];
    
    //从缓存中查询
    NSDictionary *param = @{@"search": [NSString stringWithFormat:@"%%%@%%", searchText], @"count": @50};
    NSArray *result = [CYCreditCacheTool defaultRecordWithParam:param];
    //    [self.searchResult addObjectsFromArray:result];
    self.searchResult = [NSMutableArray arrayWithArray:result];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.segmentSelected = CYIndexFirst;
    self.searchDisplayController.searchResultsTableView.frame = self.creditTableView.frame;
    
    //刷新控件
    [self setupRefreshView];
    //去除多余分割线
    [self setExtraCellLineHidden];
    //设置输入框背景图
    [self.creditSearchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield"]];
    
    _noticeview= [[UIView alloc]initWithFrame:CGRectMake(self.view.x, _creditTableView.y, _creditTableView.width, _creditTableView.height)];
    _noticeview.backgroundColor = [UIColor whiteColor];
    
    //加载黑名单数据
    //    [self loadData];
    //添加地区筛选框
    [self setupPickerView];
    //位置信息
    //    [self loadLocationInfo];
    //还款展示
    [self loadPayBacks];
    [self setupNoti];
    self.creditTableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    //加载数据
    [self newsDefaultsWithParams:nil];
}

- (void)setupRefreshView {
    //上拉刷新
    __weak typeof(self) selfVC = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        CYLog(@"进入底部刷新状态");
        [selfVC refreshFooterView:self.page];
    }];
    
    [footer setTitle:@"点击加载更多" forState:MJRefreshStateIdle];
    self.searchDisplayController.searchResultsTableView.mj_footer = footer;
    self.footer = footer;
    CYWeakObject(weakself, self);
    LEDIYFooter *diyFooter = [LEDIYFooter footerWithRefreshingBlock:^{
        NSDictionary *param = nil;
        if (weakself.city != nil && !weakself.city.isEmpty) {
            param = @{@"city": weakself.city, @"page": @(weakself.defPage)};
        } else {
            param = @{@"page": @(weakself.defPage)};
        }
        [weakself newsDefaultsWithParams:param];
    }];
    diyFooter.refreshingTitleHidden = YES;
    self.creditTableView.mj_footer = diyFooter;
}

- (void)loadData {
    //缓存中加载
    NSDictionary *param = @{@"count": @30};
    NSArray *result = [CYCreditCacheTool defaultRecordWithParam:param];
    if (result.count) {
        [self.newsDefaults addObjectsFromArray:result];//存储数据
        self.showDatas = [NSMutableArray arrayWithArray:result];//展示数据
        [self.creditTableView reloadData];
    }else {
        //        [MBProgressHUD showMessage:@"数据加载中..." toView:self.view];
    }
    //加载总记录数
    [CYCreditTool totalCountForsuccess:^(NSNumber *total) {
        self.total = total;
        [self.creditTableView reloadData];
    } failure:^(NSError *error) {
        CYLog(@"获取总数失败：%@", error);
    }];
}

- (void)refreshFooterView:(int)page {
    NSDictionary *params = @{@"condition": self.searchText, @"page":[NSString stringWithFormat:@"%d", page]};
    //发送网络请求
    [CYCreditTool defaultRecordsBySearchWithParams:params success:^(NSArray *defrs) {
        if (defrs && defrs.count) {
            //将刷新结果添加到显示数组
            [self.searchResult addObjectsFromArray:defrs];
            [self.footer  endRefreshing];
            
            [self.searchDisplayController.searchResultsTableView reloadData];
        } else {
            [self.footer endRefreshingWithNoMoreData];
            self.page = -1;
        }
        //保存搜索关键字
        if (_searchText) {
            self.searchKeyDic[_searchText] = [NSNumber numberWithInt:self.page];
            CYUserDefaultsAddObj(self.searchKeyDic, CYSearchKey);
            self.page++;
        }
    } failure:^(NSError *error) {
        [self.footer  endRefreshing];
        CYLog(@"黑名单搜索服务器请求失败：%@", error);
        [MBProgressHUD showError:CYServerConnectFailure toView:self.view];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.showDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentSelected == CYIndexFirst) {
        CYDefaultRecordCell *cell = [CYDefaultRecordCell cellWithTableView:tableView];
        CYDefaultRecordAO *defr = nil;
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            defr = self.searchResult[indexPath.row];
        }else {
            defr = self.showDatas[indexPath.row];
        }
        cell.defr = defr;
        return cell;
    }else {
        static NSString *ID = @"payBackCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        if (indexPath.row >= self.payBacks.count) {
            return cell;
        }
        CYPayBack *payBack = self.payBacks[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:12];
        cell.textLabel.numberOfLines = 0;
        NSString *dateFormat = [CYCreditTool timewithLongLongValue:payBack.createTime.longLongValue formatter:nil];
        NSString *personName = @"*";
        if (payBack.lenderPerson && ![payBack.lenderPerson isEqualToString:@""]) {
            personName = [payBack.lenderPerson substringToIndex:1];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"    %@**于%@在“中国诚信联盟”的见证下，已将款项%@元支付给%@**，履行还款义务，目前系统已对%@**进行下线。", [payBack.lenderPerson substringToIndex:1], dateFormat, payBack.price, [payBack.name substringToIndex:1], [payBack.lenderPerson substringToIndex:1]];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //设置点击选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.segmentSelected == CYIndexFirst) {
        CYDefaultRecordAO *defr = nil;
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            defr = self.searchResult[indexPath.row];
            //modal到详情页
            CYCreditDetailVC *credetail = [[CYCreditDetailVC alloc] init];
            defr.pushTag = 2;
            credetail.defr = defr;
            CYNavigationVController *nav = [[CYNavigationVController alloc] initWithRootViewController:credetail];
            [self presentViewController:nav animated:YES completion:nil];
            if (!IOS8) {
                [self.searchDisplayController setActive:NO animated:YES];//关闭searchDisplayController
            }
        }else {
            defr = self.showDatas[indexPath.row];
            CYCreditDetailVC *credetail = [[CYCreditDetailVC alloc] init];
            defr.pushTag = 1;
            credetail.defr = defr;
            credetail.hidesBottomBarWhenPushed = YES;
            //push到详情页
            [self.navigationController pushViewController:credetail animated:YES];
        }
    } else if (self.segmentSelected == CYIndexSecond) {
        
    }
}
/**
 *  要入该方法才能在查询时显示sectionHeader?
 */
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    if (self.segmentSelected == CYSegmentIndexFirst) {
//        return @" ";
//    }
//    return nil;
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.segmentSelected == CYIndexFirst) {
        UIView *headView = [[UIView alloc] initForAutoLayout];
        headView.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){16, 2, self.view.frame.size.width, 20}];
        label.font = [UIFont systemFontOfSize:13];
        [headView addSubview:label];
        UIView *bottomline = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(label.frame), self.view.frame.size.width, 1)];
        bottomline.backgroundColor = [UIColor lightGrayColor];
        [headView addSubview:bottomline];
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            label.text = [NSString stringWithFormat:@"共有%lu条记录", (unsigned long)self.searchResult.count];
        }else {
            if (self.total) {
                label.text = [NSString stringWithFormat:@"黑名单公示栏(收录总记录数:%@条)", self.total];
            }else {
                label.text = @"黑名单公示栏";
            }
        }
        return headView;
    }
    return [[UIView alloc] initForAutoLayout];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentSelected == CYIndexFirst) {
        return 105;
    }
    return 80;
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length) {
        [self.footer resetNoMoreData];
        self.searchText = searchText;
        if (self.searchKeyDic[searchText]) {
            NSNumber *page = self.searchKeyDic[searchText];
            if (page.intValue + 1) {
                self.page = page.intValue + 1;
            } else {
                [self.footer endRefreshingWithNoMoreData];
            }
        } else {
            self.page = 0;
        }
    }
}

/**
 *  键盘搜索按键监听
 *
 *  @param searchBar
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //    [MBProgressHUD showMessage:@"搜索中..." toView:self.view];
    //    [self refreshFooterView];
    if (self.searchKeyDic[self.searchText]) {
        NSNumber *page = self.searchKeyDic[self.searchText];
        if (page.intValue + 1) {
            self.page = page.intValue + 1;
        } else {
            [self.footer endRefreshingWithNoMoreData];
        }
    } else {
        self.page = 0;
        [self.footer beginRefreshing];
    }
}

/**
 *  键盘弹出:搜索框开始编辑文字
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    //隐藏导航栏
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];
    //    [UIView animateWithDuration:.3 animations:^{
    //        self.segmentView.transform = CGAffineTransformMakeTranslation(0, -self.segmentView.frame.size.height - 20);
    //    }];
    //设置输入框背景图片
    [self.creditSearchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield_hl"]];
}

#pragma mark - UISearchDisplayDelegate
/**
 *  结束搜索时显示导航栏
 */
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {
    CYLog(@"结束搜索");
    self.searchText = nil;
    //显示导航栏
    //    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //    [UIView animateWithDuration:.3 animations:^{
    //        self.segmentView.transform = CGAffineTransformIdentity;
    //    }];
    //设置输入框背景图片
    [self.creditSearchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield"]];
}

- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
    [tableView setContentInset:UIEdgeInsetsMake(50, 0, 50, 0)];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}

/**
 *  去除多余cell分割线，在tableView初始化的时候调用该方法
 *
 *  @param tableView
 */
- (void)setExtraCellLineHidden {
    UIView *view =[[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.creditTableView setTableFooterView:view];
    [self.searchDisplayController.searchResultsTableView setTableFooterView:view];
}

/**
 *  地区筛选按钮
 *
 *  @param sender
 */
- (IBAction)sifterbtn:(id)sender {
    [UIView animateWithDuration:0.3 animations:^{
        if (self.isShow) {
            self.pickerView.transform = CGAffineTransformMakeTranslation(0, -self.pickerView.height-50);
            //            self.show = NO;
            self.coverBtn.alpha = 0.5;
        } else {
            self.pickerView.transform = CGAffineTransformIdentity;
            self.show = YES;
        }
    }];
}
/*!
 *  @brief  城市选择
 */
- (void)setupPickerView {
    CYCitysPickerView *pickerView = [[CYCitysPickerView alloc] initWithPoint:CGPointMake(0, CYScreeSize.height - 110 - 48) delegate:self];
    [self.view addSubview:pickerView];
    self.pickerView = pickerView;
    self.show = YES;
    self.coverBtn.alpha = 0;
}

#pragma mark - CYCitysPickerViewDelegate
/**
 *  筛选按钮代理
 *
 *  @param view
 *  @param province
 *  @param city
 */
- (void)pickerView:(CYCitysPickerView *)view selectedProvince:(NSString *)province city:(NSString *)city {
    CYLog(@"筛选:%@, %@", province, city);
    //更新位置显示Label
    self.areaLabel.text = [NSString stringWithFormat:@"当前地区:%@-%@", province, city];
    if (!province && !city) {
        NSUserDefaults *deft = [NSUserDefaults standardUserDefaults];
        NSDictionary *areaInfo = [deft objectForKey:CYAreaInfoKey];
        if (areaInfo) {
            province = areaInfo[@"province"];
            city = areaInfo[@"city"];
            
            //更新位置显示Label
            self.areaLabel.text = [NSString stringWithFormat:@"当前地区:%@-%@", province, city];
        } else {
            province = @"省份";
            city = @"城市";
        }
    }
    
    //遮盖点击
    [self coverClick:nil];
    self.city = city;
    self.defPage = 0;
    [self.newsDefaults removeAllObjects];
    //加载刷新数据
    [self newsDefaultsWithParams:@{@"province": province, @"city": city}];
}

/**
 *  遮盖点击
 *
 *  @param sender
 */
- (IBAction)coverClick:(id)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformIdentity;
        self.coverBtn.alpha = 0;
    }];
}

#pragma mark - 地理位置信息
/**
 *  位置信息
 */
- (void)loadLocationInfo {
    if (IOS8) {
        [self.locMgr requestAlwaysAuthorization];
    }
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locMgr startUpdatingLocation];
        NSDictionary *areaInfo = [[NSUserDefaults standardUserDefaults] objectForKey:CYAreaInfoKey];
        if (!areaInfo) {
            [MBProgressHUD showMessage:@"正在获取当前位置..." toView:self.view];
        } else {
            self.areaLabel.text = [NSString stringWithFormat:@"当前地区:%@-%@", areaInfo[@"province"], areaInfo[@"city"]];
        }
    } else { // 不能定位用户的位置
        // 1.告诉用户检查网络状况
        // 2.提醒用户打开定位开关
        
        //从服务器加载数据
        [self newsDefaultsWithParams:nil];
        
        //        if (![[NSUserDefaults standardUserDefaults] objectForKey:CYFailureLocation]) [[[UIAlertView alloc] initWithTitle:nil message:CYFailureLocation delegate:nil cancelButtonTitle:CYToolTips otherButtonTitles:nil] show];
        
    }
    
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // 数组里面存放的是CLLocation对象， 一个CLLocation就代表一个位置
    CLLocation *loc = [locations lastObject];
    
    // 纬度：loc.coordinate.latitude
    // 经度：loc.coordinate.longitude
    CYLog(@"纬度=%f, 经度=%f", loc.coordinate.latitude, loc.coordinate.longitude);
    
    // 停止更新位置(不用定位服务，应当马上停止定位，非常耗电)
    [manager stopUpdatingLocation];
    
    // 根据经纬度查找地名
    [self reverseGeocodeWithLatitude:loc.coordinate.latitude longitude:loc.coordinate.longitude];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    CYLog(@"位置获取失败：%@", error);
    [MBProgressHUD hideHUDForView:self.view];
    
    //从服务器加载数据
    [self newsDefaultsWithParams:nil];
}

/**
 *  反地理编码：经纬度 -> 地名
 */
- (void)reverseGeocodeWithLatitude:(CGFloat)latitude longitude:(CGFloat)longtitude {
    
    // 开始反向编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longtitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error || placemarks.count == 0) {
            CYLog(@"你输入的经纬度找不到，可能在火星上");
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:@"获取地理位置失败"];
        } else { // 编码成功（找到了具体的位置信息）
            // 输出查询到的所有地标信息
            
            // 显示最前面的地标信息
            CLPlacemark *placemark = [placemarks firstObject];
            CYLog(@"name=%@ locality=%@ country=%@ administrativeArea=%@", placemark.name, placemark.locality, placemark.country, placemark.administrativeArea);
            NSString *locality = placemark.locality;
            NSString *administrativeArea = placemark.administrativeArea;
            
            if (!administrativeArea || !locality) {
                NSDictionary *areaInfo = [[NSUserDefaults standardUserDefaults] objectForKey:CYAreaInfoKey];
                if (!areaInfo) {
                    administrativeArea = @"云南省";
                    locality = @"昆明市";
                } else {
                    administrativeArea = areaInfo[@"province"];
                    locality = areaInfo[@"city"];
                }
            }
            self.areaLabel.text = [NSString stringWithFormat:@"当前地区:%@-%@", administrativeArea, locality];
            self.city = locality;
            //服务器加载数据
            NSDictionary *areaInfo = @{@"province": administrativeArea, @"city": locality};
            //            [self newsDefaultsWithParams:areaInfo];
            
            //本地存储地位信息
            NSUserDefaults *deft = [NSUserDefaults standardUserDefaults];
            [deft setObject:areaInfo forKey:CYAreaInfoKey];
            [deft synchronize];
            
        }
    }];
}

#pragma mark - 从服务器加载黑名单数据
/**
 *  从服务器加载黑名单数据
 *
 *  @param params 位置信息:province,city
 */
- (void)newsDefaultsWithParams:(NSDictionary *)params {
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    [MBProgressHUD showMessage:nil toView:self.view];
    [CYCreditTool newsDefaultsWithParams:params success:^(NSArray *defrs) {
        [MBProgressHUD hideHUDForView:self.view];
        if (defrs && defrs.count) {
            //        [self.newsDefaults removeAllObjects];
            [self.newsDefaults addObjectsFromArray:defrs];
            self.showDatas = self.newsDefaults;
            self.defPage++;
            [self.creditTableView.mj_footer endRefreshing];
        } else {
            [self.creditTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.creditTableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.creditTableView.mj_footer endRefreshing];
        switch (error.code) {
            case CYErrorCodeOverTime:
                [MBProgressHUD showError:CYServerConnectTimeOver toView:self.view];
                break;
                
            default:
                [MBProgressHUD showError:CYServerConnectFailure toView:self.view];
                break;
        }
        CYLog(@"获取黑名单失败：%@", error);
    }];
}

- (void)loadPayBacks {
    [CYCreditTool payBacksWithParams:nil success:^(NSArray *payBacks) {
        self.payBacks = payBacks;
    } failure:^(NSError *error) {
        CYLog(@"还款展示链接服务器失败：%@", error);
    }];
}

/**
 *  segment点击事件
 *
 *  @param sender
 */
- (IBAction)segmentClick:(id)sender {
    UISegmentedControl *segment = sender;
    self.segmentSelected = segment.selectedSegmentIndex;//保存选中按钮
    if (segment.selectedSegmentIndex == CYIndexFirst) {
        //显示搜索框以及地区筛选
        [UIView animateWithDuration:0.3 animations:^{
            self.creditSearchBar.alpha = 1;
            self.creditTableView.transform = CGAffineTransformIdentity;
        }];
        
        self.showDatas = self.newsDefaults;
        [self.creditTableView reloadData];
    } else if (segment.selectedSegmentIndex == CYIndexSecond) {
        //隐藏搜索框以及地区筛选
        self.creditSearchBar.alpha = 0;
        CGFloat tx = self.areView.frame.size.height + self.creditSearchBar.frame.size.height + 20;
        self.creditTableView.transform = CGAffineTransformMakeTranslation(0, -tx);
        
        //self.showDatas = self.payBacks;
        [self.creditTableView reloadData];
        
        //        self.tableviewConstraint.constant = 0;//底部约束
        
        //添加并启动定时器
        //        [self setupTimer];
        
        //        [self.creditTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.showDatas.count inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)autoScroll {
    CGFloat y = self.creditTableView.frame.origin.y;
    if (self.y < y + self.creditTableView.frame.size.height) {
        y = y + .1;
    }
    
    [self.creditTableView setContentOffset:CGPointMake(0, y) animated:YES];
}

/** 还款展示index */
- (NSIndexPath*)morphedIndexPathForIndexPath:(NSIndexPath*)oldIndexPath totalRows:(NSInteger)totalRows {
    return [NSIndexPath indexPathForRow:oldIndexPath.row % totalRows inSection:oldIndexPath.section];
}

#pragma mark - 违约发布
- (IBAction)releaseClick:(UIBarButtonItem *)sender {
    CYCompanyUserModel *user = [CYCompanyUserTool companyUser];
    if (user) {
        if (CYStringEqualTo(user.examineStatusName, @"审核通过")) {
            //            CYReleaseVC *release = [self.storyboard instantiateViewControllerWithIdentifier:@"CYReleaseVC"];
            //
            //            [self.navigationController pushViewController:release animated:YES];
        } else {
            CYAlertView(@"您无权进行该操作，请先进行审核");
            //            CYPersonalDetailsVController *personDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"CYPersonalDetailsVController"];
            //            [self.navigationController pushViewController:personDetail animated:YES];
        }
    } else {
        [CYJumpsTool jumpToCompanyLogin:self];
    }
}
#pragma mark - 通知
- (void)setupNoti {
    [CYNotificationCenter addObserver:self selector:@selector(search:) name:nCYCreditSearch object:nil];
}

- (void)search:(NSNotification *)noti {
    
    //    NSString *searchKey = noti.userInfo[kCYCreditSearch];
    //    if (searchKey) {
    //        [MBProgressHUD showMessage:nil toView:self.view];
    //        [CYCreditTool getNetworkCollectRecordsBySearchWithParam:@{@"condition": searchKey, @"page": @"0"} success:^(NSArray *defrs) {
    //            [MBProgressHUD hideHUDForView:self.view];
    //            [self.networkRecords removeAllObjects];
    //            [self.networkRecords addObjectsFromArray:defrs];
    //            [self.tableview reloadData];
    //        } failure:^(NSString *message, NSError *error) {
    //            [MBProgressHUD hideHUDForView:self.view];
    //            if (message) {
    //                [MBProgressHUD showError:message];
    //            } else if (error) {
    //                [MBProgressHUD showError:@"服务器连接错误"];
    //            }
    //        }];
    //    }
    
    NSString *key = noti.userInfo[kCYCreditSearch];
    if (key && !key.isEmpty) {
        self.page = 0;
        self.searchText = key;
        [self.searchResult removeAllObjects];
        [MBProgressHUD showMessage:nil toView:self.view];
        [self refreshFooterView:0];
        NSDictionary *params = @{@"condition": self.searchText, @"page":[NSString stringWithFormat:@"%d",self.page]};
        //发送网络请求
        [CYCreditTool defaultRecordsBySearchWithParams:params success:^(NSArray *defrs) {
            [self.showDatas removeAllObjects];
            if (defrs && defrs.count) {
                //将刷新结果添加到显示数组
                //                NSLog(@"defrs = %@",defrs);
                [self.showDatas addObjectsFromArray:defrs];
                [self.footer  endRefreshing];
                //  [self.searchDisplayController.searchResultsTableView reloadData];
                [_creditTableView reloadData];
                
                NSArray *testArray;
                testArray = @[ @[ @"根据年龄筛选", @"20岁以下", @"20-29", @"30-39", @"40-49", @"50-59", @"60-69", @"70-79", @"80以上"], @[@"根据性别筛选", @"男",@"女"], @[@"地区"]];
                
                MXPullDownMenu *menu = [[MXPullDownMenu alloc] initWithArray:testArray selectedColor:CYColor(100, 200, 100,1)];
                
                menu.delegate = self;
                menu.frame =  CGRectMake(self.view.x, _creditSearchBar.y-5, self.view.width, self.creditSearchBar.height);
                UILabel *notilab = [[UILabel alloc]initWithFrame:CGRectMake(self.view.x, menu.y+menu.height,self.view.width, self.view.height-menu.height-menu.y)];
                [self.view addSubview: menu];
                notilab.text = @"未找到符合条件的人";
                notilab.textAlignment = NSTextAlignmentCenter;
                [self.noticeview addSubview:notilab];
                // [self.view addSubview:menu];
            } else {
                [self.footer endRefreshingWithNoMoreData];
                self.page = -1;
                [_creditTableView reloadData];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            //保存搜索关键字
            if (_searchText) {
                self.searchKeyDic[_searchText] = [NSNumber numberWithInt:self.page];
                CYUserDefaultsAddObj(self.searchKeyDic, CYSearchKey);
                self.page++;
            }
        } failure:^(NSError *error) {
            [self.footer  endRefreshing];
            CYLog(@"黑名单搜索服务器请求失败：%@", error);
            [MBProgressHUD showError:CYServerConnectFailure toView:self.view];
        }];
        
        
    }
}

// 实现代理.
#pragma mark - MXPullDownMenuDelegate

- (void)PullDownMenu:(MXPullDownMenu *)pullDownMenu didSelectRowAtColumn:(NSInteger)column row:(NSInteger)row
{
    if (column == 0&&row==1) {
        //NSLog(@"column0row1 be click");
        self.page = 0;
        NSDictionary *params = @{@"condition": self.searchText,  @"page":[NSString stringWithFormat:@"%d",self.page ], @"age":@"1",};
        //发送网络请求
        [CYCreditTool defaultRecordsBySearchWithParams:params success:^(NSArray *defrs) {
            if (defrs && defrs.count) {
                [self.showDatas addObjectsFromArray:defrs];
                [self.footer  endRefreshing];
                [self.searchDisplayController.searchResultsTableView reloadData];
                [_creditTableView reloadData];
            } else if(defrs.count == 0) {
                //                NSLog(@"defrsclick");
                _noticeview.hidden = NO;
                [_creditTableView reloadData];
                [self.view addSubview:_noticeview];
            }
        } failure:^(NSError *error) {
            [self.footer  endRefreshing];
            CYLog(@"黑名单搜索服务器请求失败：%@", error);
            [MBProgressHUD showError:CYServerConnectFailure toView:self.view];
        }];
        
    }
    if (column == 0&&row==3) {
        
        [self.searchResult removeAllObjects];
        //        NSLog(@"column0row1 be click");
        self.page = 0;
        NSDictionary *params = @{@"condition": self.searchText,  @"page":[NSString stringWithFormat:@"%d",self.page], @"age":@"3",};
        //发送网络请求
        [CYCreditTool defaultRecordsBySearchWithParams:params success:^(NSArray *defrs) {
            if (defrs && defrs.count) {
                //将刷新结果添加到显示数组
                //                NSLog(@"defrs = %@",defrs);
                
                [self.showDatas addObjectsFromArray:defrs];
                [self.footer  endRefreshing];
                //[self.searchDisplayController.searchResultsTableView reloadData];
                [_creditTableView reloadData];
                _noticeview.hidden = YES;
                
            } else if(defrs.count == 0) {
                //                NSLog(@"defrsclick");
            }
        } failure:^(NSError *error) {
            [self.footer  endRefreshing];
            CYLog(@"黑名单搜索服务器请求失败：%@", error);
            [MBProgressHUD showError:CYServerConnectFailure toView:self.view];
        }];
        
    }
    
    
    if (column == 1){
        //        NSLog(@"column1 be click");
    }
    if (column == 2){
        //        NSLog(@"colunm2 be click");
        [UIView animateWithDuration:0.3 animations:^{
            if (self.isShow) {
                self.pickerView.transform = CGAffineTransformMakeTranslation(0, -self.pickerView.height);
                //            self.show = NO;
                self.coverBtn.alpha = 0.5;
            } else {
                self.pickerView.transform = CGAffineTransformIdentity;
                self.show = YES;
            }
        }];
        
    }
    // NSLog(@"%d -- %d", column, row);
}


#pragma mark -
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.locMgr stopUpdatingLocation];
}

- (void)dealloc {
    [self.footer endRefreshing];
    CYLog(@"信用系统销毁");
}

@end
